//
// Created by ttao on 2022/7/26.
//

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "atomicvar.h"
#ifndef COMPUTER_ZMALLOC_H
#define COMPUTER_ZMALLOC_H
#ifdef __linux__
#include <sys/mman.h>
#endif

#define update_zmalloc_stat_alloc(__n) atomicIncr(used_memory, __n);
#define update_zmalloc_stat_free(__n) atomicDecr(used_memory, __n);

static size_t used_memory = 0;              // 全局变量用于统计体统对内存的使用情况

// PREFIX_SIZE定义为系统中一个标准的size_t的大小：
// 定义这个变量的目的是将实际的空间大小保存在dts结构体之前
#if defined(__sun) || defined(__sparc) || defined(__sparc__)
#define PREFIX_SIZE (sizeof(long long))
#else
#define PREFIX_SIZE (sizeof(size_t))
#endif
#define ASSERT_NO_SIZE_OVERFLOW(sz) assert((sz) + PREFIX_SIZE > (sz))

#define MALLOC_MIN_SIZE(x) (x > 0? x : sizeof(long))

static void zmalloc_default_oom(size_t size)
{
    fprintf(stderr, "zmalloc: Out of memory trying to allocate %zu bytes\n",
            size);
    fflush(stderr);
    abort();
}

static void (*zmalloc_oom_handler) (size_t) = zmalloc_default_oom;

void *ztrymalloc_usable(size_t size, size_t * usable);
void *ztrycalloc_usable(size_t size, size_t * usable);
void *zmalloc_usable(size_t size, size_t * usable);
void *zmalloc(size_t size);
void *zcalloc_usable(size_t size, size_t * usable);
size_t zmalloc_size(void *ptr);
void *zcalloc_usable(size_t size, size_t * usable);
void *zrealloc_usable(void *ptr, size_t size, size_t * usable);
void *zrealloc(void *ptr, size_t size);

size_t zfree(void * ptr);
void zfree_usable(void *ptr, size_t *usable);

#define d_free zfree
#define d_realloc zrealloc
#define d_trymalloc_usable ztrymalloc_usable
#define d_malloc_usable zmalloc_usable
#endif //COMPUTER_ZMALLOC_H
